<?php

?>

<style>
    #userAccess-objcont {
        height: 434px;
        max-height: 484px;
        overflow: hidden;
        overflow-y: auto;
        border: #ccc solid 1px;
        position: relative;
    }
    
    #userAccess-objcont.infoExpanded {
        height: 250px;
        max-height: 300px;
    }
    
    
    
    
    .user-active li.switchOn { display: none; }
    .user-inact li.switchOff { display: none; }
    
    .user-active span.label-user-inact { display: none; }
    .user-inact span.label-user-active { display: none; }
</style>

<div class="hidden" id="userAccess-cont">
    <div class="userinfo-full well well-small" id="userAccess-userinfo"></div>
    <h3>Доступ к объектам:</h3>
    <div class="" id="userAccess-objcont">
        
    </div>
</div>



<?php /******************** TEMPLATES ****************************/ ?>

<div class="hidden" id="users-access-formAccess-templates">
    
    <div id="userInfoFull-tmpl">
        <div>
            <div class="userphoto-container pull-left min" title="{%login%}">
                <img src="<?php echo APP_HTML_DEF_AVA; ?>" data-src="{%photo%}" alt="{%login%}" class="userphoto-image">
            </div>
            
            <div class="btn-group pull-right">
                <div class="userinfo-ex-coll filter-arrow arrow-down pull-right" onclick="userinfoExpandCollapse(); return false;" style="margin-left: 15px; cursor: pointer;"></div>
                <button class="btn btn-primary" data-toggle="dropdown"><i class="icon-user icon-white"></i> Действия</button>
                <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
                <ul class="dropdown-menu">
                    <li class="userEdit"><a href="#"><i class="icon-edit"></i> Редактировать</a></li>
                    <li class="switchOff"><a href="#"><i class="icon-off"></i> Выключить</a></li>
                    <li class="switchOn"><a href="#"><i class="icon-off"></i> Включить</a></li>
                    <li class="divider"></li>
                    <li class="user-remove"><a href="#"><i class="icon-remove"></i> УДАЛИТЬ</a></li>
                </ul>
            </div>
            <div class="pull-right" style="margin-right:10px;" >
                <span class="label label-success label-user-active">Активен</span>
                <span class="label label-important label-user-inact">Неактивен</span>
            </div>
            
            
            
            
            
            <div class="userinfo-fio nowrap">{%last_name%}</div>
            <div class="userinfo-fio nowrap">{%first_name%}</div>
            <div class="userinfo-otherinfo nowrap">{%login%}</div>
        </div>
        <div style="clear:both;"> </div>
        <div style="margin: 10px; display:none;" class="userinfo-otherinfo-container" >
            <div class="userinfo-otherinfo nowrap">{%organisation%}, {%job_position%}</div>
            <div class="userinfo-otherinfo nowrap">email: {%email%}</div>
            <div class="userinfo-otherinfo nowrap">phone: {%phone%}</div>
            <div class="userinfo-otherinfo nowrap">Зарегистрирован: {%reg_date%}</div>
        </div>
    </div> 
    
    
    
    <div id="conception-tmpl">
        <div class="cat-item" id="conception-{%id%}">
            <div class="custom-checkbox pull-left" id="cnc-cb-{%id%}" style="margin: 0 5px;" onclick="cncCBClick(this); return(false);"></div>
            <div class="filter-arrow arrow-down pull-right" id="cnc-arrow-{%id%}" onclick="cncExpandCollapse('{%id%}');"></div>
            <span>{%name%}</span>
        </div>
        <div id="cnc-content-{%id%}" class="cnc-content hidden">
            {%content%}
        </div>
    </div>
    
    
    <div id="obj-tmpl">
        <div  class="object-item object-inact" id="obj_{%id%}" onclick="manageObject(this); return(false);">
            <div class="custom-checkbox pull-left" id="obj-cb-{%id%}" style="margin: 0 5px;"></div>
            {%obj_name%}
        </div>
    </div>
<?php /***********************************************************/ ?>    
    
    
</div>





<script>
Elm.Users = Elm.Users || [];
Elm.viewsData = Elm.viewsData || [];

Elm.uaUserInfoCont = $('#userAccess-userinfo');
Elm.uaUserObjCont = $('#userAccess-objcont');

function markUserInfoInact() {
    Elm.uaUserInfoCont.addClass('user-inact').removeClass('user-active');
}

function markUserInfoActive() {
    Elm.uaUserInfoCont.addClass('user-active').removeClass('user-inact');
}

function closeUserAccessDialog() {
    Elm.userAccess.dialog('close');
}


function userinfoExpandCollapse() {
    var btn = Elm.uaUserInfoCont.find('div.userinfo-ex-coll');
    var collapsed = btn.hasClass('arrow-down');
    
    if (collapsed) {
        btn.removeClass('arrow-down').addClass('arrow-up');
        Elm.uaUserObjCont.addClass('infoExpanded');
        Elm.uaUserInfoCont.find('div.userinfo-otherinfo-container').show();
        Elm.uaUserInfoCont.find('div.userphoto-container').removeClass('min');
    }
    else {
        btn.removeClass('arrow-up').addClass('arrow-down');
        Elm.uaUserObjCont.removeClass('infoExpanded');
        Elm.uaUserInfoCont.find('div.userinfo-otherinfo-container').hide();
        Elm.uaUserInfoCont.find('div.userphoto-container').addClass('min');
    }
    
}




function uaRefreshUserInfo(user) {
    var userId = user.id;
    Elm.uaUserInfoCont.html(fillTemplate('#userInfoFull-tmpl', user));
    var img = Elm.uaUserInfoCont.find('img.userphoto-image');
    img.attr('src', img.attr('data-src'));
    
    Elm.uaUserInfoCont.find('li.userEdit').click(function(){
        if (Elm.hasOwnProperty('editUser')) {
            var onChange = function(cdata) {
                reRenderUser(Elm.Users[userId]); // обновить кнопку в списке пользователей группы
                uaRefreshUserInfo(Elm.Users[userId]);
            };

            editUserDialogOpen(userId, function(cdata) {onChange(cdata);}, function(cdata) {onChange(cdata);});
        }
        return false;
    });



    Elm.uaUserInfoCont.find('li.switchOff').click(function(){
        uiConfirm({
            text: 'Деактивировать пользователя?',
            ok: function() { deactivateUser(); }
        });
        return false;
    });

    Elm.uaUserInfoCont.find('li.switchOn').click(function(){
        uiConfirm({
            text: 'Активировать пользователя?',
            ok: function() { activateUser(); }
        });
        return false;
    });

    Elm.uaUserInfoCont.find('li.user-remove').click(function(){
        uiConfirm({
            text: '<strong>Удалить пользователя?</strong><br>Эту операцию Вы не сможете отменить.',
            ok: function() { deleteUser(); }
        });
        return false;
    });
}


function openUserAccessDialog(userId, callback) {
    userId = userId || false;
    callback = callback || function() {};
    if (!userId) return;
    
    /* req */
    jsonRequest(
        'users.php',
        {
            action  : '<?php echo ACTIONS::USERS_GET_ACCESS_INFO; ?>',
            users   : [userId]
        },

        function(data) {
            if(checkSession(data)) {
                if (!data.state) {
                    uiAlert(data.message,'Error');
                    return;
                }

                if (data.hasOwnProperty('response_data') && data.response_data) {
                    var resp = data.response_data;
                    if (resp.hasOwnProperty('usersData') && resp.usersData.hasOwnProperty(userId)) {
                        var user = resp.usersData[userId];
                        Elm.Users[userId] = user;
                        
                        if (resp.hasOwnProperty('accessData') ) {
                            if (user.rang*1 < 1) markUserInfoInact();
                            else markUserInfoActive();
                            
                            /* user.actClass = 'user-inact';
                            else user.actClass = 'user-active';*/
                            uaRefreshUserInfo(user);
                            
                            Elm.uaUserObjCont.empty();
                            if (resp.hasOwnProperty('viewsData') ) {
                                Elm.uaUserObjCont.html(userObjects(resp.viewsData));
                            }
                            
                            setAccessInfo(resp.accessData[userId]);
                            
                            Elm.userAccess.userId = userId;
                            Elm.uaUserObjCont.removeClass('infoExpanded');
                            
                            Elm.userAccess.dialog('open');
                            Elm.userAccess.successCallback = callback;
                        }
                        
                    }
                }

            }
            else {
                Elm.loginFormModal.dialog('open');
                Elm.loginFormModal.successCallback = function(){
                    openUserAccessDialog(userId, callback);
                };
            }
        },

        function() {
            uiAlert('Ошибка соединения','Error');
        }
    );
    
    
    Elm.userAccess.successCallback = callback;
}

function userObjects(viewsData) {
    viewsData = viewsData || {};
    var html = '';
    
    for (var i in viewsData) {
        if (viewsData.hasOwnProperty(i)) html += renderConception(viewsData[i]);
    }
    
    
    return html;
    
}

function renderConception(cnc) {
    var data = {
        content : '',
        id      : cnc.id,
        name    : cnc.name
    };
    
    if (cnc.hasOwnProperty('children')) {
        for (var i in cnc.children) {
            if (cnc.children.hasOwnProperty(i)) data.content += renderConception(cnc.children[i]);
        }
    }
    if (cnc.hasOwnProperty('objects')) {
        for (var i in cnc.objects) {
            if (cnc.objects.hasOwnProperty(i)) data.content += renderObj(cnc.objects[i]);
        }
    }
    
    if (!data.content) return '';
    return fillTemplate('#conception-tmpl', data);
}


function renderObj(obj) {
    obj = obj || {};
    return fillTemplate('#obj-tmpl', obj);
}

function setAccessInfo(accessData) {
    accessData = accessData || []
    
    for (var i in accessData) if (accessData.hasOwnProperty(i)) {
        setObj(i, 1);
    }
    cncRefreshCB();
}



function manageObject(div) {
    var id = div.id.replace('obj_','');
    var cb = $('#obj-cb-'+id);//$(div).find('input');
    if (!cb.length) return;
    var checked = cb.hasClass('checked');

    var send = {
        user: Elm.userAccess.userId,
        object: id,
        action: checked? '<?php echo ACTIONS::USERS_DENY_ACCESS; ?>' : '<?php echo ACTIONS::USERS_ALLOW_ACCESS; ?>'
    };

    showLoader();
    jsonRequest(
        'users.php',
        send,
        function(data) {
            if(checkSession(data)) {
                if(data.hasOwnProperty('state') && data.state){
                    if (checked) {
                        $(div).addClass('object-inact').removeClass('object-selected');
                        cb.removeClass('checked');
                    }
                    else {
                        $(div).addClass('object-selected').removeClass('object-inact');
                        cb.addClass('checked');
                    }
                }
                cncRefreshCB();
            }
            else {
                Elm.loginFormModal.dialog('open');
                Elm.loginFormModal.successCallback = function(){
                    manageObject(div);
                };
            }
            
            hideLoader();

        },
        function() {
            //alert('error');
            cncRefreshCB();
            hideLoader();
        }
    );

}




function showLoader() {
    if (!Elm.uaUserObjCont.length) return;

    $('<div id="ua-loader">').css({
        position: 'absolute',
        opacity: .3,
        background: 'white',
        top: 0,
        left: 0,
        width: Elm.uaUserObjCont.outerWidth(),
        height: Elm.uaUserObjCont.outerWidth()
    }).appendTo(Elm.uaUserObjCont).click(function(){return false;});
}


function hideLoader() {
    $("#ua-loader").empty().remove();
}




function cncExpandCollapse(id) {

    var content = $('#cnc-content-'+id);
    if(!content.length) return ;

    if (content.hasClass('hidden')) {
        //expand
        content.removeClass('hidden');
        $('#cnc-arrow-'+id).removeClass('arrow-down').addClass('arrow-up');
    }
    else {
        //collapse
        content.addClass('hidden');
        $('#cnc-arrow-'+id).removeClass('arrow-up').addClass('arrow-down');
    }
}


var cncCbStates = ['checked','part'];
function setCB(cb, state) {
    state = state || false;
    cb = $(cb) || $('#none');
    cb.removeClass(cncCbStates.join(' '));
    if (state) cb.addClass(state);
}

function setObj(id, state) {
    var div = $('#obj_'+id);
    var cb = $('#obj-cb-'+id);

    if (!state) {
        $(div).addClass('object-inact').removeClass('object-selected');
        setCB(cb);
    }
    else {
        $(div).addClass('object-selected').removeClass('object-inact');
        setCB(cb, 'checked');
    }
}


function refreshConception (conc) {
    var id = conc.attr('id').replace('conception-', '');
    var content = $('#cnc-content-'+id);
    var children = content.children('.cat-item');
    var cb = $('#cnc-cb-'+id);

    children.each(function() {
        refreshConception($(this));
    });

    if (children.children('.part').length) {
        setCB(cb,'part');
        return;
    }

    // считаем чекнутые и не чекнутые подкатегории
    var cch = children.children('.checked').length;
    var call = children.children('.custom-checkbox').length;
    var cun = call-cch;

    if (cun && cch) {
        setCB(cb,'part');
        return;
    }

    cch = (cch && (cch == call)); //все категории выделены д/н
    cun = (!call || (cun == call)); //все категории не выделены д/н

    // считаем чекнутые и не чекнутые объекты
    var cobj = content.children('.object-item.object-selected').length;
    var uobj = content.children('.object-item.object-inact').length;

    // есть и те и др. объекты - частично выделено.
    if (cobj && uobj) {
        setCB(cb,'part');
        return;
    }

    // если нет категорий, то - всё однозначно.
    if (!call) {
        if (cobj) {setCB(cb,'checked');return;}
        else {setCB(cb);return;}
    }

    // комбинируем объекты и подкатегории
    if (cch && !uobj) {setCB(cb,'checked');return;}
    if (cun && !cobj) {setCB(cb);return;}
    setCB(cb,'part');
}



function cncRefreshCB() {

    var conc = Elm.uaUserObjCont.children('.cat-item');
    conc.each(function() {
        refreshConception($(this));
    });


}

function cncGetObjects(conc, recursive) {
    recursive = recursive || true;

    var id = conc.attr('id').replace('conception-', '');
    var content = $('#cnc-content-'+id);
    var cb = $('#cnc-cb-'+id);

    var out = [];

    var objects = content.children('.object-item');
    objects.each(function() {
        out.push(this.id.replace('obj_',''));
    });

    if (recursive) {
        var children = content.children('.cat-item');
        children.each(function() {
            var cobj = cncGetObjects($(this), true);
            for (var i in cobj) if (cobj.hasOwnProperty(i)) out.push(cobj[i]);
        });
    }

    return out;
}


function cncCBClick(cb) {
    var id = cb.id.replace('cnc-cb-', '');
    var jcb = $(cb);

    var cstate = '';
    if (jcb.hasClass('checked')) cstate = 'checked';
    else if (jcb.hasClass('part')) cstate = 'part';


    var obj = cncGetObjects($('#conception-'+id), true);

    var send = {
        setaccess   : cstate? 0 : 1,
        //objects     : obj,
        conception  : id,
        user        : Elm.userAccess.userId,
        action      : '<?php echo ACTIONS::USERS_SET_CNC_ACCESS; ?>'
    };

    showLoader();
    jsonRequest(
        'users.php',
        send,
        function(data) {
            if(checkSession(data)) {
                if(data.hasOwnProperty('state') && data.state){
                    for (var i in obj) {
                        if (obj.hasOwnProperty(i)) {
                            setObj(obj[i], !cstate);
                        }
                    }
                }
                cncRefreshCB();
            }
            else {
                Elm.loginFormModal.dialog('open');
                Elm.loginFormModal.successCallback = function(){
                    cncCBClick(cb);
                };
            }
            hideLoader();
        },
        function() {
            cncRefreshCB();
            hideLoader();
        }
    );
}



function deactivateUser() {
    var send = {
        user: Elm.userAccess.userId,
        action: '<?php echo ACTIONS::USERS_DEACTIVATE_USER; ?>'
    }
    showLoader();
    jsonRequest(
        'users.php',
        send,
        function(data) {
            if(checkSession(data)) {
                if(data.hasOwnProperty('state') && data.state){
                    markUserInact(Elm.userAccess.userId);
                    markUserInfoInact();
                }
                else uiAlert(data.message,'Error');
            }
            else {
                Elm.loginFormModal.dialog('open');
                Elm.loginFormModal.successCallback = function(){
                    deactivateUser();
                };
            }
            hideLoader();
        },
        function() {
            hideLoader();
        }
    );
}



function activateUser() {
    var send = {
        user: Elm.userAccess.userId,
        action: '<?php echo ACTIONS::USERS_ACTIVATE_USER; ?>'
    }
    showLoader();
    jsonRequest(
        'users.php',
        send,
        function(data) {
            if(checkSession(data)) {
                if(data.hasOwnProperty('state') && data.state){
                    markUserActive(Elm.userAccess.userId);
                    markUserInfoActive();
                }
                else uiAlert(data.message,'Error');
            }
            else {
                Elm.loginFormModal.dialog('open');
                Elm.loginFormModal.successCallback = function(){
                    activateUser();
                };
            }
            hideLoader();
        },
        function() {
            hideLoader();
        }
    );
}



function deleteUser() {
    var send = {
        user: Elm.userAccess.userId,
        action: '<?php echo ACTIONS::USERS_DELETE_USER; ?>'
    }
    showLoader();
    jsonRequest(
        'users.php',
        send,
        function(data) {
            if(checkSession(data)) {
                if(data.hasOwnProperty('state') && data.state){
                    hideUser(Elm.userAccess.userId);
                    closeUserAccessDialog();
                }
                else uiAlert(data.message,'Error');
            }
            else {
                Elm.loginFormModal.dialog('open');
                Elm.loginFormModal.successCallback = function(){
                    deleteUser();
                };
            }
            hideLoader();
        },
        function() {
            hideLoader();
        }
    );
}







    



    $(function() {
        Elm.userAccess = $('#userAccess-cont');
        //Elm.userAccessForm = $('#userAccessForm');
        Elm.userAccess.successCallback = function(data) {};
        Elm.userAccess.userId = 0;


        $('#userAccess-cancel').click(function(){
            Elm.userAccess.dialog('close');
            Elm.userAccess.userId = 0;
            return false;
        });

        Elm.userAccess.dialog({
            width       : 550,
            modal       : true,
            resizable   : false,
            title       : "Права доступа пользователя",
            autoOpen    : false,
            buttons     : {}
        }).removeClass('hidden');

        

    });


</script>